package com.pope.framework.triage.modular.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pope.framework.core.reqres.response.ResponseData;
import com.pope.framework.core.util.StringUtil;
import com.pope.framework.dict.modular.service.DictAllergicService;
import com.pope.framework.dict.modular.service.DictMedicalService;
import com.pope.framework.kernel.model.exception.RequestEmptyException;
import com.pope.framework.kernel.model.exception.ServiceException;
import com.pope.framework.kernel.model.page.PageResult;
import com.pope.framework.page.PageFactory;
import com.pope.framework.triage.modular.dto.IdNumDto;
import com.pope.framework.triage.modular.dto.MedicalCardDto;
import com.pope.framework.triage.modular.dto.PatientInfoDto;
import com.pope.framework.triage.modular.dto.TriageInfoDto;
import com.pope.framework.triage.modular.entity.PatientAllergic;
import com.pope.framework.triage.modular.entity.PatientInfo;
import com.pope.framework.triage.modular.entity.PatientMedical;
import com.pope.framework.triage.modular.service.PatientAllergicService;
import com.pope.framework.triage.modular.service.PatientInfoService;
import com.pope.framework.triage.modular.service.PatientMedicalService;
import com.pope.framework.triage.modular.vo.PatientInfoVo;
import com.pope.framework.triage.modular.vo.TriageSimpleInfoVo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Example;
import io.swagger.annotations.ExampleProperty;

@RestController
//@CrossOrigin(allowCredentials="true",maxAge = 3600)
@CrossOrigin
@RequestMapping("${spring.application.app-id}/patient")
@Api(value="患者基本信息相关API",tags= {"患者基本信息相关API"})
public class PatientInfoContoller {
	@Autowired
	private PatientInfoService patientInfoService;
	@ApiOperation(value = "根据ID获取患者明细",notes = "根据ID获取患者明细")
    @ApiImplicitParam(name = "id",value = "患者ID主键",dataType = "Integer",paramType = "path",example = "1112",required=true)
	@GetMapping("{id}")
	public ResponseData<PatientInfoVo> select(@PathVariable Integer id){
		if(id==null) {
			throw new ServiceException("患者ID不能为空，请重新确认！");
		}
		PatientInfo patientInfo=patientInfoService.getById(id);
		if(patientInfo==null) {
			throw new ServiceException("该患者信息已不存在，请重新确认!");
		}
		PatientInfoVo patientInfoVo=patientInfoService.getPatientDisplay(patientInfo);
		return ResponseData.success(patientInfoVo);
	}
	
	
	@ApiOperation(value = "根据身份证号存取患者信息",notes = "根据ID存取患者明细")
	@PostMapping("idNum")
	public ResponseData<PatientInfoVo> selectByIdNum(@RequestBody @Valid IdNumDto idNumDto, BindingResult bindingResult){
		if(idNumDto==null) {
			throw new RequestEmptyException("身份证信息不能为空，请重新确认！");
		}
		PatientInfo queryPatientInfo=new PatientInfo();
		queryPatientInfo.setIdNumber(idNumDto.getIdNumber().trim());
		queryPatientInfo.setHospitalId(idNumDto.getHospitalId());
		QueryWrapper<PatientInfo> queryPatientInfoWrapper=new QueryWrapper<>();
		queryPatientInfoWrapper.setEntity(queryPatientInfo);
		
		PatientInfo patientInfo=patientInfoService.getOne(queryPatientInfoWrapper);
		PatientInfoVo patientInfoVo=null;
		if(patientInfo!=null) {
			patientInfoVo=patientInfoService.getPatientDisplay(patientInfo);
		}else {
			PatientInfo savePatientInfo=new PatientInfo();
			savePatientInfo.setIdNumber(idNumDto.getIdNumber());
			savePatientInfo.setBirthday(idNumDto.getBirthday());
//			if(StrUtil.isNotBlank(idNumDto.getBirthday())) {
//				long year=DateUtil.betweenYear(DateUtil.parse(idNumDto.getBirthday()), DateUtil.date(), true);
//				savePatientInfo.setAge(StringUtil.toInt(year));
//			}
			savePatientInfo.setName(idNumDto.getName());
			savePatientInfo.setSex(idNumDto.getSex());
			savePatientInfo.setHospitalId(idNumDto.getHospitalId());
			patientInfoService.save(savePatientInfo);
			patientInfoVo=patientInfoService.getPatientDisplay(savePatientInfo);
		}
		return ResponseData.success(patientInfoVo);
	}
	
	
	@ApiOperation(value = "根据医疗卡号存取患者信息",notes = "根据医疗卡号存取患者信息")
	@PostMapping("medicalCard")
	public ResponseData<PatientInfoVo> selectByMedicalCard(@RequestBody @Valid MedicalCardDto medicalCardDto, BindingResult result){
		if(medicalCardDto==null) {
			throw new ServiceException("参数对象不能为空，请重新确认！");
		}
	
		PatientInfo queryPatientInfo=new PatientInfo();
		queryPatientInfo.setMedicalCardNumber(medicalCardDto.getMedicalCardNumber().trim());
		queryPatientInfo.setHospitalId(medicalCardDto.getHospitalId());
		QueryWrapper<PatientInfo> queryPatientInfoWrapper=new QueryWrapper<>();
		queryPatientInfoWrapper.setEntity(queryPatientInfo);
		
		PatientInfo patientInfo=patientInfoService.getOne(queryPatientInfoWrapper);
		PatientInfoVo patientInfoVo=null;
		if(patientInfo!=null) {
			patientInfoVo=patientInfoService.getPatientDisplay(patientInfo);
		}else {
			PatientInfo savePatientInfo=new PatientInfo();
			savePatientInfo.setIdNumber(medicalCardDto.getIdNumber());
			savePatientInfo.setBirthday(medicalCardDto.getBirthday());
//			if(StrUtil.isNotBlank(medicalCardDto.getBirthday())) {
//				long year=DateUtil.betweenYear(DateUtil.parse(medicalCardDto.getBirthday()), DateUtil.date(), true);
//				savePatientInfo.setAge(StringUtil.toInt(year));
//			}
			savePatientInfo.setName(medicalCardDto.getName());
			savePatientInfo.setSex(medicalCardDto.getSex());
			savePatientInfo.setMedicalCardNumber(medicalCardDto.getMedicalCardNumber());
			savePatientInfo.setHospitalId(medicalCardDto.getHospitalId());
			patientInfoService.save(savePatientInfo);
			patientInfoVo=patientInfoService.getPatientDisplay(savePatientInfo);
		}
		return ResponseData.success(patientInfoVo);
	}
	
	@ApiOperation(value = "添加患者信息",notes = "添加患者信息")
	@ApiImplicitParam(required=true,name="patientInfoDto",dataType="PatientInfoDto", paramType="body",examples = @Example({
        @ExampleProperty(value = "{'user':'id'}", mediaType = "application/json")
    }))
	@PostMapping("")
	public ResponseData<Integer> add(@RequestBody @Valid PatientInfoDto patientInfoDto,BindingResult bindingResult){
		if(patientInfoDto==null) {
			throw new ServiceException("存储对象为NULL，请重写确认！");
		}
		patientInfoDto.setId(null);
		Integer id=this.patientInfoService.insert(patientInfoDto);
		
		return ResponseData.success(id);
	}
	
	@ApiOperation(value = "修改患者记录",notes = "修改患者记录")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id",value = "或者ID主键",dataType = "Integer",paramType = "path",example = "1112",required=true)
		,
		@ApiImplicitParam(required=true,name="patientInfoDto",dataType="PatientInfoDto", paramType="body",examples = @Example({
	        @ExampleProperty(value = "{'user':'id'}", mediaType = "application/json")
	    }))
	})
	
	@PutMapping("{id}")
	public ResponseData update(@PathVariable("id") Integer id,@RequestBody @Valid PatientInfoDto patientInfoDto,BindingResult bindingResult){		
		if(id==null) {
			throw new ServiceException("主键ID不能为null");
		}
		if(patientInfoDto==null) {
			throw new ServiceException("存储对象为NULL，请重写确认！");
		}
		patientInfoDto.setId(id);
		this.patientInfoService.modify(patientInfoDto);
		return ResponseData.success();
	}
	@ApiOperation(value = "根据ID删除分诊明细",notes = "根据ID删除分诊明细")
    
    @ApiImplicitParam(name = "id",value = "患者ID主键",dataType = "Integer",paramType = "path",example = "1112",required=true)
	@DeleteMapping("{id}")
	public ResponseData delete(@PathVariable("id") String id){	
		if(id==null) {
			throw new ServiceException("主键ID不能为null");
		}
		this.patientInfoService.delete(id);
		return ResponseData.success();
	}
	
}
